package com.enlf.controller.admin;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.enlf.dto.*;
import com.enlf.entity.*;
import com.enlf.service.IFuncRelationService;
import com.enlf.service.IMenuPermissionService;
import com.enlf.service.IUserInfoService;
import com.enlf.service.IUserService;
import com.enlf.utils.CodeEnum;
import com.enlf.utils.EnlfConstants;
import com.enlf.utils.SystemConstants;
import com.enlf.utils.UserHolder;
import com.enlf.vo.UserInfoVo;
import com.enlf.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author renge
 * @since 2023-9-11
 */
@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminUserController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;

    @Resource
    private IMenuPermissionService menuPermissionService;

    @Resource
    private IFuncRelationService funcRelationService;

    /**
     * 发送手机验证码
     */
    @PostMapping("code")
    public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {
        //发送短信验证码并保存验证码
        return userService.sentCode(phone, session);
    }

    /**
     * 登录功能
     *
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginFormDTO loginForm, HttpSession session) {
        //  实现登录功能
        Map<String, String> result = userService.loginAdmin(loginForm, session);
        String msg = MapUtils.getString(result, "msg", CodeEnum.FAIL.getMsg());
        if (null != MapUtils.getString(result, "token", null)) {
            String token = MapUtils.getString(result, "token", null);
            return R.OK(token);
        } else {
            return R.FAIL(msg);
        }
    }

    /**
     * 登出功能
     *
     * @return 无
     */
    @PostMapping("/logout")
    public Result logout() {
        //实现登出功能
        UserHolder.removeUser();
        return Result.ok("退出登录");
    }

    @GetMapping("/me")
    public R me() {
        //获取当前登录的用户并返回
        UserDTO userDTO = UserHolder.getUser();
        UserAdminDTO userAdminDTO = new UserAdminDTO();
        BeanUtils.copyProperties(userDTO, userAdminDTO);
        List<MenuPermission> menuPermissions = userService.queryAdminPermission(userDTO.getId());
        if (CollectionUtils.isNotEmpty(menuPermissions)) {
            userAdminDTO.setMenuPermissionList(menuPermissions);
        }
        return R.OK(userAdminDTO);
    }

    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long userId) {
        // 查询详情
        User user = userService.getById(userId);
        UserInfo info = userInfoService.getById(userId);
        UserInfoDTO userInfoDTO = UserInfoDTO.builder()
                .id(user.getId())
                .nickName(user.getNickName())
                .password(user.getPassword())
                .phone(user.getPhone())
                .birthday(info != null && info.getBirthday() != null ? info.getBirthday().format(DateTimeFormatter.ISO_LOCAL_DATE) : null)
                .build();

        if (info != null) {
            // 没有详情，应该是第一次查看详情
            BeanUtils.copyProperties(info, userInfoDTO, "birthday");
        }
        // 返回
        return R.OK(userInfoDTO);
    }

    /**
     * 用户列表
     *
     * @param current
     * @return
     */
    @GetMapping("/userList")
    public R funcList(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        UserDTO userDTO = UserHolder.getUser();
        //查询用户是否有超级管理员权限
        FuncRelation isAdmin = funcRelationService.findByUserIdAdmin(userDTO.getId(), EnlfConstants.ADMIN_FUNC.FUNC_ADMIN.getFuncId());
        if (null == isAdmin) {
            return R.FAIL("您无权限操作");
        }
        // 根据类型分页查询
        Page<User> page = userService.query()
                .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE_TEN));
        List<UserVo> userList = page.getRecords().stream().map(user ->{
            UserVo userVo = BeanUtil.copyProperties(user,UserVo.class);
            List<FuncRelation> funcRelationList = funcRelationService.list(new QueryWrapper<FuncRelation>().eq("USER_ID", userVo.getId()));
            userVo.setFuncRelationList(funcRelationList);
            return userVo;
        }).collect(Collectors.toList());
        Map<String, Object> result = new HashMap<>();
        result.put("total", page.getTotal());
        result.put("list", userList);
        return R.OK(result);
    }

    @GetMapping("/user/{id}")
    public Result queryUserById(@PathVariable("id") Long userId) {
        // 查询详情
        User user = userService.getById(userId);
        if (user == null) {
            return Result.ok();
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // 返回
        return Result.ok(userDTO);
    }
    @PutMapping("/editUser")
    public R editUserById(UserInfoVo userInfoVo) {
        // 查询详情
        User user = userService.getById(userInfoVo.getId());
        if (user == null) {
            return R.FAIL();
        }
        userService.updateUser(userInfoVo);

        // 返回
        return R.OK();
    }

    @PostMapping("/saveUser")
    public R saveUserById(UserInfoVo userInfoVo) {
        // 查询详情
        User user = userService.getById(userInfoVo.getId());
        if (user != null) {
            return R.FAIL();
        }
        userService.saveUser(userInfoVo);
        // 返回
        return R.OK();
    }


    /**
     * 编辑用户提交保存
     *
     * @return
     */
    @PutMapping(value = "/updateUser")
    public R updateUser(UserInfoVo userInfoVo) {
        User user = BeanUtil.copyProperties(userInfoVo,User.class);
        UserInfo userInfo = BeanUtil.copyProperties(userInfoVo, UserInfo.class);
        userInfo.setUserId(user.getId());
        boolean isSuccess = userService.updateById(user);
        UserInfo userInfo1 = userInfoService.getById(userInfo.getUserId());
        if (userInfo1 == null) {
            userInfoService.save(userInfo);
        } else {
            userInfoService.updateById(userInfo);
        }
        return isSuccess ? R.OK() : R.FAIL();
    }

    /**
     * 根据id删除用户
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/user/{id}")
    public R delUser(@PathVariable(value = "id") Integer id) {
        boolean isSuccess = userService.removeById(id);
        UserInfo userInfo = userInfoService.getById(id);
        if (null != userInfo){
            userInfoService.removeById(id);
        }

        return isSuccess ? R.OK() : R.FAIL();
    }

    /**
     * 根据id批量删除用户
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/user/batch")
    public R batchDelUser(@RequestParam(value = "ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        boolean isSuccess = userService.removeByIds(idList);
        userInfoService.removeByIds(idList);
        return isSuccess ? R.OK() : R.FAIL();
    }

}
